package cn.jkgly.utils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "CallBackServlet", urlPatterns = "/callBack")
public class CallBackServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + AuthUtil.APPID +
                "&secret=" + AuthUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");

//        String tokenRefreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token" +
//                "?appid=APPID" +
//                "&grant_type=refresh_token" +
//                "&refresh_token=REFRESH_TOKEN";

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        req.setAttribute("info", userInfo);
        req.getRequestDispatcher("/register").forward(req, resp);
//        System.out.println(userInfo);
    }
}
